/**
 * 功能集成器 - 负责 MediaPipe Pose 和纯蒙版功能的集成
 */
import { PureMaskController, PURE_MASK_PRESETS } from '../../features/pure-mask'
import { PoseDetectionService, type PoseDetectionResult, type PoseDetectionState } from '../../features/mediapipe-pose/PoseDetectionService'
import { DEFAULT_POSE_DETECTION_INTERVAL } from '../../config/mediapipe'
import type { DetectionArea } from '../../types'

/**
 * 功能集成器类
 */
export class FeatureIntegration {
  // 纯蒙版控制器
  private pureMaskController: PureMaskController
  
  // MediaPipe Pose 检测
  private poseDetectionService: PoseDetectionService | null = null
  private poseDetectionResult: PoseDetectionResult | null = null
  private poseDetectionTimestamp = 0
  private poseDetectionInFlight: Promise<DetectionArea[]> | null = null
  private detectionInterval = DEFAULT_POSE_DETECTION_INTERVAL

  private video: HTMLVideoElement | null = null
  private debugMode: boolean

  constructor(debugMode: boolean = false) {
    this.debugMode = debugMode
    
    // 初始化纯蒙版控制器
    this.pureMaskController = new PureMaskController({
      maskConfig: PURE_MASK_PRESETS.TRANSPARENT,
      debugMode: true
    })
  }

  /**
   * 初始化可视化器
   */
  initVisualizer(ctx: CanvasRenderingContext2D): void {
    this.pureMaskController.initVisualizer(ctx)
  }

  /**
   * 设置视频元素
   */
  setVideo(video: HTMLVideoElement | null): void {
    this.video = video
  }

  /**
   * 设置 MediaPipe Pose 检测（非阻塞）
   */
  setupPoseDetection(enableDetection: boolean): void {
    if (!enableDetection) {
      return
    }

    // 异步初始化，不阻塞构造函数
    // console.log('🚀 开始设置 MediaPipe Pose 检测（后台加载）...')
    this.poseDetectionService = new PoseDetectionService()
    
    // 在后台异步初始化，不等待完成
    this.poseDetectionService.initialize().then(() => {
      // console.log('✅ MediaPipe Pose 检测初始化成功')
      }).catch((_error) => {
      // console.warn('⚠️ MediaPipe Pose 检测初始化失败，将使用模拟检测:', error)
      this.poseDetectionService = null
      
      if (this.debugMode) {
        // console.log('🔧 调试信息: 由于 MediaPipe 无法加载，系统将使用模拟的人物检测区域进行演示')
      }
    })
  }

  /**
   * 重新加载 Pose 检测
   */
  reloadPoseDetection(): void {
    if (!this.video) return
    
    // console.log('🔄 重新加载 MediaPipe Pose 检测...')
    
    // 清理旧的检测服务（异步，不等待）
    if (this.poseDetectionService) {
        this.poseDetectionService.close().catch((_err) => {
        // console.warn('清理旧检测服务时出错:', err)
      })
    }
    
    // 重置状态
    this.poseDetectionResult = null
    this.poseDetectionInFlight = null
    this.poseDetectionTimestamp = 0
    this.poseDetectionService = null
    
    // 重新初始化（非阻塞）
    this.setupPoseDetection(true)
  }

  /**
   * 获取 Pose 检测状态
   */
  getPoseDetectionState(): PoseDetectionState {
    return this.poseDetectionService ? this.poseDetectionService.getState() : {
      initialized: false,
      initializing: false,
      modelLoaded: false,
      runningMode: 'VIDEO',
      error: undefined,
    }
  }

  /**
   * 处理 Pose 检测
   */
  processPoseDetection(timestamp: number): DetectionArea[] {
    // 如果 MediaPipe 服务不可用，返回空数组（不显示检测区域）
    if (!this.poseDetectionService || !this.video) {
      return []
    }

    const shouldRequest = timestamp - this.poseDetectionTimestamp >= this.detectionInterval
    if (shouldRequest && !this.poseDetectionInFlight) {
      this.poseDetectionTimestamp = timestamp
      this.poseDetectionInFlight = this.poseDetectionService
        .detect(this.video, timestamp)
        .then(result => {
          this.poseDetectionResult = result
          return result.areas
        })
        .catch((_error) => {
          // console.warn('Pose detection failed:', error)
          this.poseDetectionResult = null
          return []  // 检测失败时返回空数组
        })
        .finally(() => {
          this.poseDetectionInFlight = null
        })
    }

    // 如果有检测结果，返回检测区域；否则返回空数组
    if (this.poseDetectionResult?.areas?.length) {
      return this.poseDetectionResult.areas
    }

    return []  // 默认返回空数组
  }

  /**
   * 切换蒙版模式
   */
  toggleMaskMode(enabled?: boolean): boolean {
    if (enabled !== undefined) {
      this.pureMaskController.updateMaskConfig({ enabled })
      // console.log(`🎭 纯蒙版效果: ${enabled ? '开启' : '关闭'}`)
      return enabled
    } else {
      // 切换状态
      const currentConfig = this.pureMaskController.getConfig()
      const newEnabled = !currentConfig.enabled
      this.pureMaskController.updateMaskConfig({ enabled: newEnabled })
      // console.log(`🎭 纯蒙版效果: ${newEnabled ? '开启' : '关闭'}`)
      return newEnabled
    }
  }

  /**
   * 设置纯蒙版透明度
   */
  setPureMaskOpacity(opacity: number): void {
    this.pureMaskController.setMaskOpacity(opacity)
    // console.log(`🎭 纯蒙版透明度: ${(opacity * 100).toFixed(0)}%`)
  }

  /**
   * 获取纯蒙版控制器
   */
  getPureMaskController(): PureMaskController {
    return this.pureMaskController
  }

  /**
   * 设置检测间隔
   */
  setDetectionInterval(interval: number): void {
    this.detectionInterval = interval
  }

  /**
   * 获取检测间隔
   */
  getDetectionInterval(): number {
    return this.detectionInterval
  }

  /**
   * 清理资源
   */
  destroy(): void {
    if (this.poseDetectionService) {
      this.poseDetectionService.close()
      this.poseDetectionService = null
      this.poseDetectionResult = null
    }
  }
}

